
let socket = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

export const initWebSocket = (token, callback) => {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  socket = new WebSocket(`${protocol}//localhost:5051/ws?tocken=${tocken}`);

  socket.onopen = () => {
    console.log('WebSocket connected');
    reconnectAttempts = 0;
    // 发送初始化请求
    socket.send(JSON.stringify({
      payload: { userId: "123" }
    }));
  };

  socket.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('Received data:', data);

      // 根据后端返回的数据类型处理
      switch (data.type) {
        case 'CONTACTS_LIST':
          callback(data.contacts); // 处理联系人列表
          break;
        case 'MESSAGE':
          handleIncomingMessage(data.message); // 处理单条消息
          break;
        case 'INIT_DATA':
          // 处理完整的初始化数据（包含联系人、未读消息等）
          callback(data.payload);
          break;
        default:
          console.warn('Unknown message type:', data.type);
      }
    } catch (error) {
      console.error('Failed to parse WebSocket message:', error);
    }
  };

  socket.onclose = () => {
    console.log('WebSocket disconnected');
    if (reconnectAttempts < maxReconnectAttempts) {
      setTimeout(() => {
        reconnectAttempts++;
        initWebSocket(token, callback);
      }, Math.min(1000 * reconnectAttempts, 30000));
    }
  };

  socket.onerror = (error) => {
    console.error('WebSocket error:', error);
  };
};

// 发送普通消息的示例
export const sendMessage = (messageDto) => {
  if (socket?.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({
      type: 'SEND_MESSAGE',
      payload: messageDto
    }));
  } else {
    console.error('WebSocket is not connected');
  }
};

export const closeWebSocket = () => {
  if (socket) {
    socket.close();
    socket = null;
  }
};
